package com.kynnnn.cloud.quartz.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;


@Configuration
public class SchedulerConfig {

    //执行任务。有了触发器，我们就可以执行任务了。注册一个SchedulerFactroyBean,然后将触发器一list的方式传入
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource,
                                                     @Qualifier("jobOneTrigger") Trigger jobOneTrigger){
        SchedulerFactoryBean schedulerFactoryBean=new SchedulerFactoryBean();
        //调度器名称
        schedulerFactoryBean.setSchedulerName("TestScheduler");
        //数据源
        schedulerFactoryBean.setDataSource(dataSource);
        //覆盖已存在的任务,用于Quartz集群，QuartzScheduler启动会更新已存在的Job
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //延时1s启动定时任务，避免系统未完全启动却开始执行定时任务的情况
        schedulerFactoryBean.setStartupDelay(1);
        //设置加载的quartz.properties配置文件
        schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
        //自动启动
        schedulerFactoryBean.setAutoStartup(true);
        //注册触发器
        schedulerFactoryBean.setTriggers(jobOneTrigger);

        return schedulerFactoryBean;
    }

}
